package demo.practice.leetcode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

public class P101_new {

    //未解出来，
    //结题思路  层序遍历（通过队列层序遍历)，然后通过栈做对称校验
    //[2,3,3,4,5,5]
    //    2
    //  3   3
    // 4 5 5
    public static void main(String[] args) {
        P101_new p101 = new P101_new();
        TreeNode root = new TreeNode(2);
        root.left = new TreeNode(3);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.left = new TreeNode(5);
        System.out.println(p101.isSymmetric(root));
    }

    public boolean isSymmetric(TreeNode root) {
        if(root==null)
            return true;

        LinkedList<TreeNode> list = new LinkedList<>();
        if (root.left != null)
            list.add(root.left);
        if (root.right != null)
            list.add(root.right);

        while (!list.isEmpty()) {
            if (list.size() % 2 != 0)
                return false;

            Stack<TreeNode> nds = new Stack<>();
            int len=list.size() / 2;
            for (int i = 0; i < len; i++) {
                if(list.peek()!=null){
                    list.add(list.peek().left);
                    list.add(list.peek().right);
                }
                nds.add(list.poll());
            }

            while (!nds.empty()) {
                if(list.peek()!=null){
                    list.add(list.peek().left);
                    list.add(list.peek().right);
                }
                TreeNode bf = nds.pop();
                TreeNode af = list.poll();
                if ((bf == null || af == null) && bf != af)
                    return false;
                if (bf != null && bf.val != af.val)
                    return false;
            }
        }
        return true;
    }


}
